package hhm.android.my

import android.net.Uri
import android.os.Bundle
import android.text.TextUtils
import android.view.View
import androidx.databinding.DataBindingUtil
import com.alibaba.android.arouter.facade.annotation.Route
import com.trello.rxlifecycle4.RxLifecycle
import com.trello.rxlifecycle4.android.ActivityEvent
import hhm.android.library.LogUtils
import hhm.android.library.datePicker.bean.DateParams
import hhm.android.library.utils.*
import hhm.android.my.databinding.ActivityMyProfileBinding
import siau.android.base.*
import siau.android.base.enum.HeightClass
import siau.android.base.enum.WeightClass
import siau.android.http.model.ChangeIdentityRequest
import siau.android.http.model.UserInfoModel
import siau.android.library.FileUtil
import java.text.SimpleDateFormat
import java.util.*
import kotlin.properties.Delegates


@Route(path = MY_ROUTE)
class MyProfileActivity : SBBaseActivity() {

    lateinit var dataBinding: ActivityMyProfileBinding
    private var userInfoModel: UserInfoModel? = null
    lateinit var bottomSingleIdentitySelectSheet: BottomSingleIdentitySelectSheet
    lateinit var bottomSingleSexSelectSheet: BottomSingleGenderSelectSheet
    var weightCla = ""
    var heightCla = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setTitleWhiteAndTextBlank()
        dataBinding = DataBindingUtil.setContentView(this, R.layout.activity_my_profile)
        initTitleWithLine(getString(R.string.my_profile))
        dataBinding.lifecycleOwner = this

        when (SBApplication.userData.weightUnit) {
            WeightClass.KG.msg -> weightCla = getString(R.string.class_kg)
            WeightClass.JIN.msg -> weightCla = getString(R.string.class_jin)
            WeightClass.LB.msg -> weightCla = getString(R.string.class_bang)
        }
        when (SBApplication.userData.heightUnit) {
            HeightClass.CM.msg -> heightCla = getString(R.string.class_cm)
            HeightClass.FT.msg -> heightCla = getString(R.string.class_ft)
        }

        bottomSingleIdentitySelectSheet = BottomSingleIdentitySelectSheet(this, BottomSingleIdentitySelectSheet.SELECT_MOTHER, dataBinding.activityMyProfileChangeIdentityTv.text.toString(), object : GetStringListener {
            override fun getString(s: String) {
                showLoadingFragment(R.id.activity_my_profile_fl)

                var identityType by Delegates.notNull<Int>()
                var identityName = ""

                when (bottomSingleIdentitySelectSheet.selectType) {
                    BottomSingleIdentitySelectSheet.SELECT_MOTHER -> {
                        identityType = BottomSingleIdentitySelectSheet.SELECT_MOTHER
                    }
                    BottomSingleIdentitySelectSheet.SELECT_FATHER -> {
                        identityType = BottomSingleIdentitySelectSheet.SELECT_FATHER

                    }
                    BottomSingleIdentitySelectSheet.SELECT_OTHER -> {
                        identityType = BottomSingleIdentitySelectSheet.SELECT_OTHER
                        identityName = s
                    }
                }

                val r = ChangeIdentityRequest(userInfoModel?.familyId!!, identityType, s, 1)
                HttpHelper().changeIdentity(r)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
                    removeLoadingFragment()

                    userInfoModel?.identityType = identityType
                    SBApplication.userData.identityType = identityType
                    userInfoModel?.userIdentity = identityName
                    SBApplication.userData.userIdentity = identityName
                    dataBinding.activityMyProfileChangeIdentityTv.text = when (identityType) {
                        1 -> {
                            getString(R.string.mother)
                        }
                        2 -> {
                            getString(R.string.father)
                        }
                        else -> {
                            identityName
                        }
                    }
                }, {
                    removeLoadingFragment()
                    showToast(it.message)
                })
            }
        })
        var sexInt = 0
        if (userInfoModel != null && userInfoModel?.sex != null) {
            sexInt = userInfoModel?.sex!!
        }
        bottomSingleSexSelectSheet = BottomSingleGenderSelectSheet(this, sexInt, object : GetStringListener {
            override fun getString(s: String) {
                dataBinding.activityMyProfileSexTv.text = s
                userInfoModel?.sex = bottomSingleSexSelectSheet.selectType
                updateData()
            }
        })
        dataBinding.activityMyProfileBirthday.setOnClickListener {
            DialogUtils.showDatePicBottomView(
                this,
                object : GetDateListener {
                    override fun getDate(date: Date, string: String) {
                        dataBinding.activityMyProfileBirthdayTv.text = string
                        userInfoModel?.birthday = date.time
                        updateData()
                    }
                },
                "yyyy/MM/dd",
                DateParams.TYPE_YEAR, DateParams.TYPE_MONTH, DateParams.TYPE_DAY,
            )
        }
        dataBinding.activityMyProfileChangeIdentity.setOnClickListener {
            if (userInfoModel != null && bottomSingleIdentitySelectSheet != null) {
                bottomSingleIdentitySelectSheet.initSelect(userInfoModel?.identityType!!)
            }
            bottomSingleIdentitySelectSheet.show()
        }
        dataBinding.activityMyProfileHeight.setOnClickListener {
            DialogUtils.showHeightPicBottomView(this, SBApplication.userData.heightUnit, if (userInfoModel?.height?.isNaN() == true) {
                20.00
            } else {
                userInfoModel?.height!!
            }, object : GetStringListener {
                override fun getString(s: String) {
                    dataBinding.activityMyProfileHeightTv.text = analyseDataBeforeSet(s, 2, heightCla)
                    userInfoModel?.height = s.replace("cm", "").toDouble()
                    updateData()
                }
            })
        }
        dataBinding.activityMyProfileSex.setOnClickListener {
            bottomSingleSexSelectSheet.show()
        }
        dataBinding.activityMyProfileName.setOnClickListener {
            getStringDialog(this, getString(R.string.input_nike_name), "", object : GetStringListener {
                override fun getString(s: String) {
                    updateData(s)
                }
            })
        }

        val takePhotoResult = registerForActivityResult(TakePhotoActivityResultContact()) {
            if (it.resultCode != RESULT_OK) {
                return@registerForActivityResult
            }
            if (!TextUtils.isEmpty(TakePhotoPopWindowUtils.mTempPhotoPath)) {
                showLoadingFragment(R.id.activity_my_profile_fl)

                //将图片显示在ivImage上
                HttpHelper().getQiNiuInfo()?.subscribe({ authTokenResponse ->
                    SBApplication.uploadManager.put(TakePhotoPopWindowUtils.mTempPhotoPath, "android" + Date().time + ".jpg", authTokenResponse.authToken, { key, info, res ->
                        //res 包含 hash、key 等信息，具体字段取决于上传策略的设置
                        TakePhotoPopWindowUtils.mTempPhotoPath = ""

                        if (info.isOK) {

                            userInfoModel!!.userAvatar = authTokenResponse.domain + key
                            HttpHelper().editUserInfo(userInfoModel!!)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({ a ->
                                GlideUtils.loadCircleImageNoCache(this, userInfoModel!!.userAvatar, dataBinding.activityMyProfileIcon, R.mipmap.take_picture, R.mipmap.take_picture)
                                SBApplication.userData.avatarUrl = userInfoModel!!.userAvatar
                                removeLoadingFragment()
                            }, { t ->
                                removeLoadingFragment()
                                showToast(t.message)
                            })
                            //将照片显示在 ivImage上

                        } else {
                            LogUtils.Companion.i("qiniu", "Upload Fail")
                            removeLoadingFragment()
                        }
                    }, null)

                }, { throwable ->
                    removeLoadingFragment()
                    showToast(throwable.message)
                })
            }
        }
        val selectPicResult = registerForActivityResult(TakePhotoActivityResultContact()) {

            if (it.intent == null || it.intent!!.data == null) {
                return@registerForActivityResult
            }
            showLoadingFragment(R.id.activity_my_profile_fl)
            val uri: Uri = it.intent?.data!!
            val filePath: String = FileUtil.getFilePathByUri(this, uri)

            if (!TextUtils.isEmpty(filePath)) {
                HttpHelper().getQiNiuInfo()?.subscribe({ authTokenResponse ->
                    SBApplication.uploadManager.put(filePath, "android" + Date().time + ".jpg", authTokenResponse.authToken, { key, info, res ->
                        //res 包含 hash、key 等信息，具体字段取决于上传策略的设置
                        if (info.isOK) {

                            userInfoModel!!.userAvatar = authTokenResponse.domain + key
                            HttpHelper().editUserInfo(userInfoModel!!)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({ a ->
                                GlideUtils.loadCircleImageNoCache(this, userInfoModel!!.userAvatar, dataBinding.activityMyProfileIcon, R.mipmap.take_picture, R.mipmap.take_picture)
                                SBApplication.userData.avatarUrl = userInfoModel!!.userAvatar
                                removeLoadingFragment()
                            }, { t ->
                                removeLoadingFragment()
                                showToast(t.message)
                            })
                            //将照片显示在 ivImage上

                        } else {
                            LogUtils.Companion.i("qiniu", "Upload Fail")
                            removeLoadingFragment()
                        }
                    }, null)

                }, { throwable ->
                    removeLoadingFragment()
                    showToast(throwable.message)
                })
            } else {
                removeLoadingFragment()
            }
        }

        dataBinding.activityMyProfileIconLl.setOnClickListener(object : OnMultiClickListener() {
            override fun onMultiClick(v: View?) {
                TakePhotoPopWindowUtils.takePhoto(this@MyProfileActivity, dataBinding.activityMyProfileContent, takePhotoResult, selectPicResult)
            }
        })

        initData()
    }

    private fun initData() {
        showLoadingFragment(R.id.activity_my_profile_fl)
        HttpHelper().getUserInfo()?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
            removeLoadingFragment()
            userInfoModel = it
            if (!userInfoModel?.userAvatar.isNullOrEmpty()) {
                GlideUtils.loadCircleImageNoCache(this, userInfoModel?.userAvatar!!, dataBinding.activityMyProfileIcon, R.mipmap.take_picture, R.mipmap.take_picture)
                SBApplication.userData.avatarUrl = userInfoModel?.userAvatar!!
            }
            if (!userInfoModel?.nickName.isNullOrEmpty()) {
                dataBinding.activityMyProfileNameTv.text = userInfoModel?.nickName
                SBApplication.userData.nickName = userInfoModel?.nickName!!
            }
            if (userInfoModel?.sex == 1) {
                dataBinding.activityMyProfileSexTv.text = getString(R.string.boy)
            } else if (userInfoModel?.sex == 2) {
                dataBinding.activityMyProfileSexTv.text = getString(R.string.girl)
            }
            if (userInfoModel?.birthday != null && userInfoModel?.birthday!! > 0) {
                val sdf = SimpleDateFormat("yyyy/MM/dd")
                dataBinding.activityMyProfileBirthdayTv.text = sdf.format(userInfoModel?.birthday)
            }
            dataBinding.activityMyProfileHeightTv.text = if (userInfoModel?.height == null) {
                getString(R.string.please_select)
            } else {
                analyseDataBeforeSet(userInfoModel?.height.toString(), 2, heightCla)
            }
            when (userInfoModel?.identityType) {
                1 -> {
                    dataBinding.activityMyProfileChangeIdentityTv.text = getString(R.string.mother)
                }
                2 -> {
                    dataBinding.activityMyProfileChangeIdentityTv.text = getString(R.string.father)
                }
                3 -> {
                    dataBinding.activityMyProfileChangeIdentityTv.text = userInfoModel?.userIdentity
                }
            }
            dataBinding.activityMyProfilePhone.text = userInfoModel?.mobile
        }, {
            removeLoadingFragment()
            showToast(it.message)
        })
    }

    private fun updateData() {
        showLoadingFragment(R.id.activity_my_profile_fl)
        HttpHelper().editUserInfo(userInfoModel!!)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
            removeLoadingFragment()
        }, {
            removeLoadingFragment()
            showToast(it.message)
        })
    }

    private fun updateData(nickName: String) {
        userInfoModel?.nickName = nickName
        showLoadingFragment(R.id.activity_my_profile_fl)
        HttpHelper().editUserInfo(userInfoModel!!)?.compose(RxLifecycle.bindUntilEvent(lifecycle(), ActivityEvent.STOP))?.subscribe({
            removeLoadingFragment()
            dataBinding.activityMyProfileNameTv.text = nickName
            SBApplication.userData.nickName = nickName
        }, {
            userInfoModel?.nickName = SBApplication.userData.nickName
            removeLoadingFragment()
            showToast(it.message)
        })
    }
}